
AR ?= ar
CC ?= gcc
PREFIX ?= /usr/local

CFLAGS = -O2 -Werror  -Wall

TEST_SRCS = $(wildcard test/*.c)
SRCS = $(wildcard src/*.c)
INCS = $(wildcard src/*.h)
OBJS = $(SRCS:.c=.o)


MAJOR_VERSION = 0
MINOR_VERSION = 1
PATCH_VERSION = 3

BUILD_DIR = build
TARGET = libsqueue
TARGET_A  = $(TARGET).a
TARGET_SO = $(TARGET).so.$(MAJOR_VERSION).$(MINOR_VERSION).$(PATCH_VERSION)


all: $(TARGET_A) $(TARGET_SO)

install: all
	test -d $(PREFIX)/lib || mkdir -p $(PREFIX)/lib
	cp -f $(BUILD_DIR)/$(TARGET_A) $(PREFIX)/lib/$(TARGET_A)
	cp -f $(BUILD_DIR)/$(TARGET_SO) $(PREFIX)/lib/$(TARGET_SO)
	ln -sf $(PREFIX)/lib/$(TARGET_SO) $(PREFIX)/lib/$(TARGET).so.$(MAJOR_VERSION).$(MINOR_VERSION)
	ln -sf $(PREFIX)/lib/$(TARGET_SO) $(PREFIX)/lib/$(TARGET).so.$(MAJOR_VERSION)
	ln -sf $(PREFIX)/lib/$(TARGET_SO) $(PREFIX)/lib/$(TARGET).so
	test -d $(PREFIX)/include || mkdir -p $(PREFIX)/include/
	cp -f $(INCS) $(PREFIX)/include/

uninstall:
	rm -f $(PREFIX)/lib/$(TARGET_A)
	rm -f $(PREFIX)/lib/$(TARGET)*
	for x in $(notdir $(INCS)); do rm -f $(PREFIX)/include/$$x; done


$(TARGET_A): $(OBJS)
	@mkdir -p $(BUILD_DIR)
	$(AR) rcs $@ $^
	mv $@ $(BUILD_DIR)

# ld -z now -shared -lc -soname `basename $@` src/*.o -o $@
$(TARGET_SO): $(OBJS)
	@mkdir -p $(BUILD_DIR)
	$(CC) -fPIC -shared $(SRCS) -o $@
	@strip --strip-unneeded --remove-section=.comment --remove-section=.note $@
	@mv $@ $(BUILD_DIR)

bin/test: $(TEST_SRCS) $(OBJS)
	@mkdir -p bin
	$(CC) $^ -o $@

bin/benchmark: benchmark.o $(OBJS)
	@mkdir -p bin
	$(CC) $^ -o $@


%.o: %.c
	$(CC) $< $(CFLAGS) -c -o $@

clean:
	rm -rf bin build *.o src/*.o

test: bin/test
	@./$<

benchmark: bin/benchmark
	@./$<

.PHONY: test benchmark clean install uninstall
